package com.ruoyi.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.constant.SysConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 雪花ID生成工具类
 * @author yjf
 * @date 2022-07-08
 */
@Component
@Slf4j
public class SnowflakeUtils {
    private SnowflakeUtils() {
    }

    /**
     * 设置终端ID
     **/
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private static Long workerId = SysConstants.LONG_0;
    /**
     * 数据中心ID
     **/
    private static final Long DATACENTER_ID = SysConstants.LONG_1;
    private static final Snowflake SNOWFLAKE = IdUtil.createSnowflake(workerId, DATACENTER_ID);

    /**
     *启动时获取终端ID
     **/
    @PostConstruct
    public void init() {
        workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        log.info("当前终端ID", workerId);
    }

    /**
     * 获取默认雪花id
     *
     * @return long
     **/
    public static synchronized Long snowflakeId() {
        return SNOWFLAKE.nextId();
    }

    /**
     * 根据输入的终端ID和数据中心ID获取默认雪花id
     *
     * @return long
     **/
    public static synchronized Long snowflakeId(Long workerId, Long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }
}
